package cn.demoxy.utils;

import cn.hutool.core.io.IoUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @auther demo
 * @date 2021/6/13 12:46
 * 提供excel,文件导出和下载
 */
public class FileUtils {
    /**
     * 下载excel文件的方法
     *
     * @param filePath excel文件的路径
     * @param response
     */
    public static void downLoadExcel(String filePath, HttpServletResponse response) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File file = new File(filePath);
            inputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            //截取后面的字符串
            String filename = filePath.substring(filePath.lastIndexOf("\\"));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
            response.flushBuffer();
        } catch (IOException e) {
        } finally {
            try {
                if (outputStream != null) outputStream.close();
                if (inputStream != null) inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void downLoadZip(String filePath, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setCharacterEncoding("UTF-8");
        //截取后面的字符串
        String filename = filePath.substring(filePath.lastIndexOf("\\")+1);
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        // 定义输出类型
        response.setContentType("application/zip");

        File file = new File(filePath);
        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            ) {
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void delDir(String path){
        File dir=new File(path);
        if(dir.exists()){
            File[] tmp=dir.listFiles();
            for(int i=0; i<tmp.length; i++){
                if(tmp[i].isDirectory()){
                    delDir(path+"/"+tmp[i].getName());
                }
                else{
                    tmp[i].delete();
                }
            }
            dir.delete();
        }
    }

}
